#include "Udpserver.hpp"
#include "Log.hpp"
#include <memory>
#include <cstdio>
#include <vector>
#include <string>

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << "port[1024+]\n"
              << std::endl;
}

// 代码分用
std::string Handler(const std::string &info, const std::string &clientip, uint16_t clientport)
{
    std::cout << "[" << clientip << ": " << clientport << "]#" << info << std::endl;
    std::string res = "Server get a message: ";
    res += info;
    std::cout << res << std::endl;

    return res;
}
// 场景一，实现命令
bool SafeCheck(const std::string &cmd)
{
    std::vector<std::string> key_word = {
        "rm",
        "mv",
        "cp",
        "kill",
        "sudo",
        "unlink",
        "uninstall",
        "yum",
        "tcp",
        "while"};
    for (auto &word : key_word)
    {
        auto pos = cmd.find(word);
        if (pos != std::string::npos)
            return false; // 在你的命令中找到上面任意一个的话，就是不合法的，直接返回falsse
    }
    return true;
}
std::string ExcuteCommand(const std::string &cmd)
{
    std::cout << "get a request cmd: " << cmd << std::endl;
    if (!SafeCheck(cmd))
        return "Bad man";

    FILE *fp = popen(cmd.c_str(), "r");
    if (fp == NULL)
    {
        perror("popen");
        return "error";
    }
    std::string result;
    char buffer[4096];
    while (true)
    {
        char *ok = fgets(buffer, sizeof(buffer), fp);
        if (ok == nullptr)
            break; // 为空了，说明读完了
        result += buffer;
    }
    pclose(fp);
    return result;
}

// ./Udpserver port 直接把端口号暴露给命令行，由命令行来决定使用哪个端口
int main(int argc, char *argv[])
{
    if (argc != 2) // argc表示命令行中命令个数
    {
        Usage(argv[0]);
        exit(0);
    }
    uint16_t port = std::stoi(argv[1]); // 字符串转整数
    std::unique_ptr<Udpserver> svr(new Udpserver(port));
    svr->Init(); // 初始化
    // svr->Run(Handler); // 服务器启动，可以传入自定义方法，实现代码分层
    // svr->Run(ExcuteCommand); // 场景一，实现命令
    svr->Run(); // 服务器启动

    return 0;
}
